#include <stdio.h>
#include <string.h>
#include "Storage.h"
#include "SymInfo.h"

Storage::Storage(size_t initLength) :
		length(initLength) {
	store = new char[length];

	lastBlockSize = length;
	lastBlock = store;

	startFreeSpace = (store + sizeof(char*));
	sizeFree = lastBlockSize;
}

Storage::~Storage() {
	delete[] store; // TODO: fix bug with invalid cleanup
}

void Storage::expand() {
	lastBlockSize *= 2;
	static char* newBlock;
	newBlock = new char[lastBlockSize];

	writeNextBlockPosition(newBlock);
	lastBlock = newBlock;

	startFreeSpace = newBlock + sizeof(char*);
	*((char**) (lastBlock)) = NULL;
	/*for (int i = 0; i <= 4; i++) {
	 lastBlock[i] = NULL;
	 }*/
	sizeFree = lastBlockSize;
}

void Storage::writeNextBlockPosition(char* next) {
	*((char**) lastBlock) = next;
}

char* Storage::allocSpace(size_t wordLength) {
	if (sizeFree < wordLength) {
		this->expand();
	}
	return startFreeSpace;
}

Key Storage::insert(char* lexem, TokenType type) {
	char* lastStartFreeSpace = startFreeSpace;
	size_t wdLength = lexem[0];

	// why copy? lexem is already at the right place
	// memcpy(startFreeSpace, lexem, wdLength * sizeof(char));
	startFreeSpace = startFreeSpace + wdLength;
	sizeFree = sizeFree - wdLength;

	SymInfo* currentSymInfo = new SymInfo(lastStartFreeSpace, type);
	return currentSymInfo;
}

